package com.my.geojson.mybatis.config.jts.extend;

import com.my.geojson.mybatis.config.jts.converter.GenericGeometryConverter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.locationtech.jts.geom.Geometry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * 〈功能简述〉<br>
 * 〈JtsGeometryTypeHandler实现通用的geometry类型转org.locationtech.jts.geom.Geometry及其实现类〉
 *
 * @author Mr.QL
 * @ClassName JtsGeometryTypeHandler
 * @Date 2021-12-10 16:58
 * @Version 1.0
 */
@SuppressWarnings("unchecked")
@MappedTypes(Geometry.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class JtsGeometryTypeHandler extends BaseTypeHandler<Geometry> {

    static final GenericGeometryConverter GEOMETRY_CONVERTER = new GenericGeometryConverter();

    public JtsGeometryTypeHandler() {

    }

    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, GEOMETRY_CONVERTER.to(parameter, ps.getConnection().getMetaData().getDatabaseProductName()));
    }

    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return GEOMETRY_CONVERTER.from(rs.getObject(columnName), rs.getStatement().getConnection().getMetaData().getDatabaseProductName());
    }

    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return GEOMETRY_CONVERTER.from(rs.getObject(columnIndex), rs.getStatement().getConnection().getMetaData().getDatabaseProductName());
    }

    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return GEOMETRY_CONVERTER.from(cs.getObject(columnIndex), cs.getConnection().getMetaData().getDatabaseProductName());
    }
}
